import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'dart:async';
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import 'audio_training_result_page.dart';

class AudioTrainingPage extends StatefulWidget {
  @override
  _AudioTrainingPageState createState() => _AudioTrainingPageState();
}

class _AudioTrainingPageState extends State<AudioTrainingPage> {
  final FlutterTts tts = FlutterTts();
  int totalQuestions = 10;
  int currentQuestion = 1;
  late int a, b, correctAnswer;
  String userInput = '';
  late DateTime startTime;
  Timer? countdownTimer;
  int timeLeft = 3;
  int questionDurationSetting = 3; // Add this line
  String difficulty = '10以内加减法';

  List<int> responseTimes = [];
  List<bool> correctness = [];

  // 从SharedPreferences加载设置
  Future<void> _loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    if (mounted) {
      setState(() {
        questionDurationSetting = prefs.getInt('audioQuestionDuration') ?? 3;
        timeLeft =
            questionDurationSetting; // Initialize timeLeft with the loaded setting
        totalQuestions = prefs.getInt('audioTrainingQuestions') ?? 10;
        difficulty = prefs.getString('audioTrainingDifficulty') ?? '10以内加减法';
      });
    }
  }

  @override
  void initState() {
    super.initState();
    // 初始化语音播放完成回调
    tts.setCompletionHandler(() {
      if (mounted) {
        setState(() {
          startTime = DateTime.now();
          _startTimer();
        });
      }
    });
    
    _loadSettings().then((_) {
      if (mounted) {
        setState(() {});
        _nextQuestion();
      }
    });
  }

  void _nextQuestion() {
    if (currentQuestion > totalQuestions) {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (_) => AudioTrainingResultPage(correctness: correctness, responseTimes: responseTimes)),
      );
      return;
    }

    final rand = Random();
    String question;

    // 根据难度设置生成不同的题目
    switch (difficulty) {
      case '10以内加减法':
        a = rand.nextInt(10);
        b = rand.nextInt(10);
        if (rand.nextBool()) {
          correctAnswer = a + b;
          question = '$a 加 $b 是多少';
        } else {
          // 确保结果为正数
          if (a < b) {
            final temp = a;
            a = b;
            b = temp;
          }
          correctAnswer = a - b;
          question = '$a 减 $b 是多少';
        }
        break;

      case '20以内加减法':
        a = rand.nextInt(20);
        b = rand.nextInt(20);
        if (rand.nextBool()) {
          correctAnswer = a + b;
          question = '$a 加 $b 是多少';
        } else {
          // 确保结果为正数
          if (a < b) {
            final temp = a;
            a = b;
            b = temp;
          }
          correctAnswer = a - b;
          question = '$a 减 $b 是多少';
        }
        break;

      case '20以内连加连减':
        a = rand.nextInt(10);
        b = rand.nextInt(10);
        final c = rand.nextInt(10);
        if (rand.nextBool()) {
          correctAnswer = a + b + c;
          question = '$a 加 $b 加 $c 是多少';
        } else {
          // 确保结果为正数
          int result = a;
          String q = '$a';
          if (rand.nextBool()) {
            result += b;
            q += ' 加 $b';
          } else {
            result -= b;
            q += ' 减 $b';
          }
          if (rand.nextBool()) {
            result += c;
            q += ' 加 $c';
          } else {
            result -= c;
            q += ' 减 $c';
          }
          correctAnswer = result;
          question = '$q 是多少';
        }
        break;

      case '50以内连加连减':
        a = rand.nextInt(30);
        b = rand.nextInt(20);
        final c = rand.nextInt(20);
        if (rand.nextBool()) {
          correctAnswer = a + b + c;
          question = '$a 加 $b 加 $c 是多少';
        } else {
          // 确保结果为正数
          int result = a;
          String q = '$a';
          if (rand.nextBool()) {
            result += b;
            q += ' 加 $b';
          } else {
            result -= b;
            q += ' 减 $b';
          }
          if (rand.nextBool()) {
            result += c;
            q += ' 加 $c';
          } else {
            result -= c;
            q += ' 减 $c';
          }
          correctAnswer = result;
          question = '$q 是多少';
        }
        break;

      case '表内乘法':
        a = rand.nextInt(9) + 1;
        b = rand.nextInt(9) + 1;
        correctAnswer = a * b;
        question = '$a 乘以 $b 是多少';
        break;

      default:
        a = rand.nextInt(10);
        b = rand.nextInt(10);
        correctAnswer = a + b;
        question = '$a 加 $b 是多少';
    }

    userInput = '';
    // 重置计时器为设置的时长
    if (mounted) {
      // Add mounted check
      setState(() {
        timeLeft = questionDurationSetting;
      });
    }
    _speak(question);

    setState(() {});
  }

  void _speak(String text) async {
    await tts.setLanguage("zh-CN");
    await tts.speak(text);
  }

  void _startTimer() {
    countdownTimer?.cancel();
    countdownTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        timeLeft--;
        if (timeLeft <= 0) {
          _submitAnswer();
        }
      });
    });
  }

  void _submitAnswer() {
    countdownTimer?.cancel();
    final duration = DateTime.now().difference(startTime).inMilliseconds;
    int? answer = int.tryParse(userInput);
    bool correct = answer == correctAnswer;
    responseTimes.add(duration);
    correctness.add(correct);

    currentQuestion++;
    _nextQuestion();
  }

  void _appendInput(String value) {
    if (userInput.length < 2) {
      setState(() {
        userInput += value;
      });
    }
  }

  void _clearInput() {
    setState(() {
      userInput = '';
    });
  }

  @override
  void dispose() {
    tts.stop();
    countdownTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('听算挑战')),
      body: Column(
        children: [
          SizedBox(height: 20),
          Text('题目 $currentQuestion / $totalQuestions',
              style: TextStyle(fontSize: 20)),
          SizedBox(height: 10),
          Text('剩余时间：$timeLeft 秒',
              style: TextStyle(fontSize: 20, color: Colors.red)),
          SizedBox(height: 30),
          Text(
            '你的答案：$userInput',
            style: TextStyle(fontSize: 32),
          ),
          SizedBox(height: 20),
          GridView.count(
            crossAxisCount: 3,
            mainAxisSpacing: 10,
            crossAxisSpacing: 10,
            shrinkWrap: true,
            childAspectRatio: 1.2,
            physics: NeverScrollableScrollPhysics(),
            padding: EdgeInsets.all(20),
            children: [
              ...List.generate(9, (i) {
                return ElevatedButton(
                  onPressed: () => _appendInput('${i + 1}'),
                  child: Text('${i + 1}', style: TextStyle(fontSize: 20)),
                  style: ElevatedButton.styleFrom(
                    minimumSize: Size(30, 30),
                    padding: EdgeInsets.zero,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                );
              }),
              ElevatedButton(
                onPressed: _clearInput,
                child: Text('清除'),
                style: ElevatedButton.styleFrom(
                  minimumSize: Size(30, 30),
                  padding: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: () => _appendInput('0'),
                child: Text('0', style: TextStyle(fontSize: 20)),
                style: ElevatedButton.styleFrom(
                  minimumSize: Size(30, 30),
                  padding: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: _submitAnswer,
                child: Text('OK'),
                style: ElevatedButton.styleFrom(
                  minimumSize: Size(30, 30),
                  padding: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
